package com.wnnight.wys.web.payment;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnnight.wys.entity.PageBean;
import com.wnnight.wys.entity.config.ChargeConfig;
import com.wnnight.wys.entity.lanlord.Landlord;
import com.wnnight.wys.entity.payment.PayMentMethod;
import com.wnnight.wys.entity.payment.PayMentRecords;
import com.wnnight.wys.excelHandler.PayMentRecordsHandler;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.payment.PayMentService;
import com.wnnight.wys.vo.PayMentVo;
import com.wnnight.wys.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: PayMentController
 * @Description: //账单控制器
 * @author: LJC
 * @date: 2022/8/29-10:05
 */
@RestController
@RequestMapping("/api/v1/pay")
@Slf4j
public class PayMentController {
    @Autowired
    private PayMentService payMentService;

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('pay:add')")
    public ResultVo<?> add(@RequestBody PayMentRecords payMentRecords){
        System.out.println(payMentRecords);
        payMentService.addPayMent(payMentRecords);
        return ResultVo.SUCCESS;
    }
    //获取所有缴费记录
    @PostMapping("/allList")
    public ResultVo<?> allList(@RequestBody @Validated PageBean<PayMentRecords> pageBean){

        PageBean<List<PayMentRecords>> payMent = payMentService.getAllPayMent(pageBean);
        return new ResultVo<>(payMent);
    }
    //修改
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('pay:update')")
    public ResultVo<?> update(@RequestBody PayMentRecords payMentRecords){
        PayMentRecords p = new PayMentRecords();
        p.setId(payMentRecords.getId());
        p.setBillingStatus("1");
        boolean b = payMentService.updateById(p);
        if(b){
            return ResultVo.SUCCESS;
        }else {
            return ResultVo.FAIL;
        }
    }
    //多条件分页查询
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('pay:list')")
    public ResultVo<?> findPayMent(@RequestBody PayMentVo payMentVo){
        System.out.println(payMentVo);
        log.debug("账单编号: {}",payMentVo.getBillNum());
        log.debug("所属房屋: {}",payMentVo.getTHouse());
        log.debug("业主姓名: {}", payMentVo.getLName());
        log.debug("账目类别ID: {}",payMentVo.getPmId());
        log.debug("支付方式: {}",payMentVo.getCcId());
        log.debug("当前页: {}", payMentVo.getPageBean().getCurrPage());
        log.debug("当前页数量: {}", payMentVo.getPageBean().getPageSize());
        PageBean<List<PayMentRecords>> pageBean = payMentService.getPayMent(payMentVo);
        return new ResultVo<>(pageBean);
    }
    //业主id分页查询
    @PostMapping("/findPayMentyz")
    public ResultVo<?> findPayMentyz(@RequestBody PayMentVo payMentVo, HttpServletRequest request){
        String jwt = request.getHeader("jwt");
        Integer id =(Integer) JwtUtils.getInfo(jwt, "id");
        log.debug("业主id: {}", id);
        payMentVo.getPayMentRecords().getLandlord().setId(id);
        PageBean<List<PayMentRecords>> pageBean = payMentService.getByLandlordId(payMentVo);
        return new ResultVo<>(pageBean);
    }
    //返回账单类目
    @PostMapping("/getConfigList")
    public ResultVo<?> getConfigList(){
        List<ChargeConfig> list = payMentService.getConfigList();
        return new ResultVo<>(list);
    }
    //返回支付方式
    @PostMapping("/getPayMMList")
    public ResultVo<?> getPayMMList(){
        List<PayMentMethod> list = payMentService.getPayMentMethod();
        return new ResultVo<>(list);
    }
    //下载Excel文档
    @PostMapping("/download")
    @PreAuthorize("hasAuthority('pay:download')")
    public void download (@RequestBody PayMentVo payMentVo, HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "1800");//30分钟
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, token");
        response.setHeader("Access-Control-Expose-Headers", "jwt");

        List<PayMentRecords> allList = payMentService.getAllList();

        try{
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                String fileName = URLEncoder.encode("测试", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                // 这里需要设置不关闭流
                EasyExcel.write(response.getOutputStream(), PayMentRecords.class).registerWriteHandler(new PayMentRecordsHandler()).autoCloseStream(Boolean.FALSE).sheet("模板")
                        .doWrite(allList);
            } catch (Exception e){
                // 重置response
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.writeValue(response.getWriter(), ResultVo.ERROR);
                response.getWriter().flush();
                response.getWriter().close();

        }

    }

    //返回业主
    @PostMapping("/getPayLandlordList")
    public ResultVo<?> getPayLandlordList(){
        List<Landlord> landlordList = payMentService.getPayLandlordList();
        return new ResultVo<>(landlordList);
    }
    //返回房屋
    @PostMapping("/getPayRoomList")
    public ResultVo<?> getPayRoomList(){
        List<Map<String, Object>> payRoomList = payMentService.getPayRoomList();
        return new ResultVo<>(payRoomList);
    }
}
